import axios from "axios"
import store from '@/store/index.js'

axios.defaults.timeout = 60000;

// axios.defaults.transformRequest = [function (data) {
//   if (Object.prototype.toString.call(data) != '[object FormData]') {
//     let src = ''
//     for (let item in data) {
//       src += encodeURIComponent(item) + '=' + encodeURIComponent(data[item] === null ? '' : data[item]) + '&'
//     }
//     return src;
//   } else {
//     return data;
//   }
// }]

// 请求拦截
axios.interceptors.request.use(config => {
  // config.headers['Content-Type'] = "application/json; charset=UTF-8";
  config.headers['Content-Type'] = "application/x-www-form-urlencoded";
  return config;
}, err => {
  return Promise.reject(err);
})

//  响应拦截
axios.interceptors.response.use((res) => {
  if (res.data.code == 200) {
    console.log("响应拦截数据",res)
    let isLogin = res.data.is_login;
    let isLoginState = store.state.isLogin;
    if(isLogin && isLogin != isLoginState) {
      store.dispatch('changeIsLogin', res.data.is_login)
    }
    return Promise.resolve(res.data)
  } else {
    return Promise.reject(new Error(res.data.status_desc || 'Error'));
  }
}, (err) => {
  return Promise.reject(err)
})

let request = {
  get: function (url, params = {}) {
    return new Promise((resolve, reject) => {
      axios.get(url, {
        params: params
      }).then(response => {
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  post: function (url, data) {
    return new Promise((resolve, reject) => {
      axios.post(url, data).then(response => {
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default request